﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

/// <summary>
/// 快递的数据管理器
/// </summary>
public class ExpressDataManager : Singleton<ExpressDataManager> {

    private const string key_gallary_localdata = "key_gallary_localdata";

    public TotalGallayImageData TotalGallayInfo { get; set; }

    public ExpressSetting ExpSetting { get; set; }

    public ExpressWebService ExpWebService { get; set; }

    public Dictionary<uint, GallayImageData> TotalGallayInfoDic { get; private set; }

    public Dictionary<uint, TableProto.ExpressPhotosInfo> tableProto;

    public int TotalGallaryCount
    {
        get {
            return TotalGallayInfo.totalPhotoNum;
        }
    }

    public int TotalGallayGettedCount
    {
        get {
            int sum = 0;
            foreach (var item in TotalGallayInfoDic.Values)
                if (!string.IsNullOrEmpty(item._url))
                    sum++;

            return sum;
        }
        set { }
    }

    private Dictionary<uint, GallayLocalData> m_dic_tatalGallaylocaldata;
    public Dictionary<uint, GallayLocalData> TotalGallayImageLocalData
    {
        get
        {
            if (m_dic_tatalGallaylocaldata == null)
            {
                m_dic_tatalGallaylocaldata = new Dictionary<uint, GallayLocalData>();
                TotalGallayLocalData m_tatalGallaylocaldata = PlayerPrefsX.GetXml<TotalGallayLocalData>(key_gallary_localdata, new TotalGallayLocalData());
                TotalGallayInfo.lastNewaddPicture = m_tatalGallaylocaldata.lastNewAddID;
                Debug.Log("bbbbbbbbbbbbbb==========" + TotalGallayInfo.lastNewaddPicture);
                if (m_tatalGallaylocaldata.m_tatal_gallaylocaldata.Count > 0)
                    foreach (GallayLocalData item in m_tatalGallaylocaldata.m_tatal_gallaylocaldata)
                        if (!m_dic_tatalGallaylocaldata.ContainsKey(item.m_id))
                            m_dic_tatalGallaylocaldata.Add(item.m_id, item);
            }
            return m_dic_tatalGallaylocaldata;
        }
    }

    public void TotalGallayLocalDataSave()
    {
        TotalGallayLocalData totallocaldata = new TotalGallayLocalData();
        totallocaldata.lastNewAddID = TotalGallayInfo.lastNewaddPicture;
        Debug.Log("cccccccccccccc==========" + totallocaldata.lastNewAddID);
        foreach (GallayLocalData item in TotalGallayImageLocalData.Values)
        {
            totallocaldata.m_tatal_gallaylocaldata.Add(item);
        }
        PlayerPrefsX.SetXml<TotalGallayLocalData>(key_gallary_localdata, totallocaldata);
    }



    public override void Init()
    {
        base.Init();
        TotalGallayInfo = new TotalGallayImageData(null,false,0);
        TotalGallayInfoDic = new Dictionary<uint, GallayImageData>();
        ExpSetting = new ExpressSetting(0, "0");
        tableProto = TableProtoLoader.ExpressPhotosInfoDict;
        ExpWebService = ExpressWebService.Instance;
    }

    public void InitServerData(Action onsuccess,Action onfail)
    {
        GetTotalGallaryDataFromServer(() =>
        {
            ProcessServerData();

            if (onsuccess != null) onsuccess();


        }, () => {
            if (onfail != null) onfail();
        });

    }

    public void ProcessServerData()
    {
        TotalGallayInfoDic.Clear();
        if (TotalGallayInfo._totalGallayData.Count > 0)
        {
            for (int i = 0; i < TotalGallayInfo._totalGallayData.Count; i++)
            {
                GallayImageData d = TotalGallayInfo._totalGallayData[i];
                TotalGallayInfoDic.Add(d._id, d);
            }

        }

        EventBus.Instance.BroadCastEvent(EventID.ON_EXPRESS_DATA_INIT_FINISHED);
    }

    public override void UnInit()
    {
        base.UnInit();

        Dispose();
    }

    public void GetTotalGallaryDataFromServer(Action callback,Action fail)
    {
        ExpWebService.GetDeliveryData((data) => {

            List<GallayImageData> galaryDataList = new List<GallayImageData>();
            List<Cmd.PhotoInfo> photos = data.my_photo_info;
            Dictionary<string, Cmd.PhotoInfo> netphotoDic = new Dictionary<string, Cmd.PhotoInfo>();
            foreach (var item in photos)
                netphotoDic.Add(item.photo_id, item);

            TotalGallayInfo._totalGallayData = galaryDataList;
            TotalGallayInfo.totalPhotoNum = data.total_photo_num;

            foreach (TableProto.ExpressPhotosInfo tablePhotoInf in tableProto.Values)
            {
               
                GallayImageData temp = new GallayImageData();

                switch (tablePhotoInf.area_type)
                {
                    case 1: temp._continent = Continent.NorthAmerica; break;
                    case 2: temp._continent = Continent.Australia; break;
                    case 3: temp._continent = Continent.Africa; break;
                    case 4: temp._continent = Continent.SouthAmerica; break;
                    case 5: temp._continent = Continent.Europe; break;
                    case 6: temp._continent = Continent.Asia; break;
                    default:
                        break;
                }

                temp._id = tablePhotoInf.id;
                temp._imagename = tablePhotoInf.title;
                temp.isNewAdded = TotalGallayImageLocalData.ContainsKey(tablePhotoInf.id) ? TotalGallayImageLocalData[temp._id].m_isNewadd : false;

                string netphotoID = tablePhotoInf.id.ToString();
                if (netphotoDic.ContainsKey(netphotoID))
                {
                    temp._url = tablePhotoInf.photo_url;   //查询本地表获取图片路径
                }
                else
                {
                    temp._url = null;
                }

                galaryDataList.Add(temp);
            }

            ExpSetting._energy = data.energy;
            ExpSetting._time_bonus = data.bonus_energy_time;

            if (callback != null) callback();

        }, fail);


    }

    public void InsertGalaryPhoto(Cmd.PhotoInfo netInfo)
    {
        uint id = uint.Parse(netInfo.photo_id);

        string url = TotalGallayInfoDic[id]._url;
        TotalGallayInfoDic[id].isNewAdded = true;
        TotalGallayInfo.lastNewaddPicture = id;
        //if (!TotalGallayImageLocalData.ContainsKey(id))
        //{
        //    GallayLocalData data = new GallayLocalData();data.m_id = id;data.m_isNewadd = false;
        //    TotalGallayImageLocalData.Add(id, data);
        //}
           
        //TotalGallayLocalDataSave();

        if (string.IsNullOrEmpty(url))
        {
            TotalGallayInfoDic[id]._url = tableProto[id].photo_url;
        }
        else
        {
            Debug.Log("这张图片获取过了");
        }
    }

    public bool RemovePower(int amount)
    {
        Debug.LogFormat("准备移除{0}个钻石", amount);
        if (ExpSetting._energy >= amount)
        {
            ExpSetting._energy -= amount;

            return true;
        }

        return false;
    }

    public bool AddPower(int amount)
    {
        Debug.LogFormat("获得{0}个钻石",amount);
        if (ExpSetting != null)
        {
            ExpSetting._energy += amount;
            return true;
        }

        return false;
        
    }

    public void StartTravel(Action<Cmd.PhotoInfo> photoNetInfo, Action<ExpressImageLocalLoadRuturnArg> callback,Action localloadError)
    {
        ExpWebService.StartTravel((data) => {

            Cmd.PhotoInfo photoInf = data.photo_info;
            if (photoNetInfo != null) photoNetInfo(photoInf);   //服务器返回的数据

            
            uint id = uint.Parse(photoInf.photo_id);
            string title = tableProto[id].title;
            string url = tableProto[id].photo_url;
            MonoInstane.Instance.StartCoroutine(LoadTexture(new ExpressImageLocalloadArg(id, url, title), callback, localloadError));    //图片下载的数据

        },localloadError);
    }

    /// <summary>
    /// 本地加载图片
    /// </summary>
    public IEnumerator LoadTexture(ExpressImageLocalloadArg loadArg, System.Action<ExpressImageLocalLoadRuturnArg> callback, Action localLoadFail)
    {
        uint imgid = loadArg._id;
        string localpath = loadArg._localpath;

        MonoInstane.Instance.StartCoroutine(ExpressResManager.Instance.LoadTexture(new ExpressImageLocalloadArg(imgid, localpath, loadArg._name), (tex) =>
        {
            if (callback != null) callback(tex);

        }, localLoadFail));//本地图片加载失败了
        yield break;
    }

    public void Dispose()
    {
        TotalGallayInfo = null;
        ExpSetting = null;
        ExpWebService = null;
        TotalGallayInfoDic = null;
    }

}
